package com.li.anima;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;

import com.li.widget.CircleImageView;
import com.ndboo.reslibrary.R;

/**
 * Author: Li
 * Date: 2017/8/30
 * Description: 动画
 */

public class Animations {
    /**
     * 显示加入购物车动画
     *
     * @param activity  界面
     * @param startView 动画开始
     * @param endView   动画结束
     * @param drawable  需要显示的drawable
     */
    public static void showAddAnimation(final Activity activity, View startView, final View endView, Drawable drawable) {
        if (drawable == null) {
            drawable = ContextCompat.getDrawable(activity, R.drawable.ic_goods_default);
        }
        final CircleImageView imageView = new CircleImageView(activity);
        final ViewGroup group = (ViewGroup) activity.getWindow().getDecorView();
        final PathMeasure pathMeasure = new PathMeasure();

        imageView.setImageDrawable(drawable);
        int[] startLocation = new int[2];
        int[] endLocation = new int[2];
        startView.getLocationOnScreen(startLocation);
        endView.getLocationOnScreen(endLocation);
        WindowManager.LayoutParams params = new WindowManager.LayoutParams(-2, -2);
        params.width = 100;
        params.height = 100;

        group.addView(imageView, params);
        Path path = new Path();
        path.moveTo(startLocation[0], startLocation[1]);
        path.quadTo(0, (startLocation[1] + endLocation[1]) / 2,
                endLocation[0], endLocation[1]);
        pathMeasure.setPath(path,false);

        ValueAnimator animator = ValueAnimator.ofFloat(0, pathMeasure.getLength());
        animator.setDuration(1000);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                float[] pos = new float[2];
                pathMeasure.getPosTan(value, pos, new float[2]);
                imageView.setTranslationX(pos[0]);
                imageView.setTranslationY(pos[1]);

            }
        });
        animator.addListener(
                new AnimatorListener() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        group.removeView(imageView);
                        Animation animation1 = AnimationUtils.loadAnimation(activity, R.anim.anim_add_cart);
                        endView.startAnimation(animation1);
                    }
                }
        );
        animator.start();
    }
}
